<script setup lang="ts">
import { createConsultOrder, getConsultOrderPayUrl, getConsultOrderPre, getPatientDetail } from '@/services/consult'
import { useConsultStore } from '@/stores/consult'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { Dialog, showFailToast, showConfirmDialog, showLoadingToast, showDialog } from 'vant'
import { ref, onMounted } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
// 获取订单相关信息
const store = useConsultStore()
const payInfo = ref<ConsultOrderPreData>()
const loadPayinfo = async () => {
  const res = await getConsultOrderPre({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  console.log(res)
  payInfo.value = res.data
  // 存储优惠券信息
  store.setCoupon(res.data.couponId)
}

// 获取患者相关信息
const patient = ref<Patient>()
const loadPatient = async () => {
  if (store.consult.patientId) {
    const res = await getPatientDetail(store.consult.patientId)
    patient.value = res.data
  }
}

onMounted(() => {
  if (!store.consult.type || !store.consult.illnessType || !store.consult.depId) {
    return showDialog(
      {
        title: '温馨提示',
        message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
        closeOnPopstate: false
      }).then(() => {
        router.push('/')
      })
  }
  loadPayinfo()
  loadPatient()
})

//生成订单  展示支付方式抽屉
const loading = ref(false)
const agree = ref(false) //同意用户支付协议
const show = ref(false) // 控制抽屉显示隐藏
const orderId = ref() //订单id
const paymentMethod = ref<0 | 1>() //支付方式 0是微信  1是支付宝
const openSheet = async () => {
  if (!agree.value) return showFailToast('请同意用户支付协议')
  loading.value = true
  const res = await createConsultOrder(store.consult)   // 生成订单
  orderId.value = res.data.id
  store.clear() // 生成完订单 前端不需要存信息了，清除存储的信息
  loading.value = false
  show.value = true  // 展示抽屉
}
//支付功能前步骤----------- 1 隐藏 抽屉的关闭按钮 2再关闭抽屉的时候,确认弹框提示 ,仍要关闭 跳转订单, 继续支付 关闭确认框
// 3 如果已经生成订单了  回退的时候拦截 4 生成支付地址然后跳转:调后台接口 5刷新页面的时候 判断是否问诊记录存在  不存在 提示,确认之后回到首页
const router = useRouter()
const onClose = () => {
  return showConfirmDialog({
    title: '温馨提示',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    confirmButtonText: '继续支付',
    cancelButtonText: '仍要关闭'
  })
    .then(() => {
      // 不想关闭
      return false
    })
    .catch(() => {
      // 想关闭 防止有orderId 后，onBeforeRouteLeave 会拦截跳转
      orderId.value = ''
      router.push('/user/consult')
      return true
    })
}
onBeforeRouteLeave(() => { // 离开当前路由
  // 如果生成订单了 不让离开
  if (orderId.value) return false
})
// 跳转支付
const pay = async () => {
  if (paymentMethod.value === undefined) return showFailToast('请选择支付方式')
  showLoadingToast({ message: '支付中.....' })
  if (orderId.value) {
    const res = await getConsultOrderPayUrl({
      paymentMethod: paymentMethod.value, //支付方式
      orderId: orderId.value, // 订单id
      payCallback: 'http://127.0.0.1:5173/room' //回调地址 或者 'http://localhost:5173/room'
    })
    location.href = res.data.payUrl
  }
}
// 进页面 判断记录清空，初始化校验
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <!-- 支付信息 -->
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment.toFixed(2)}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 患者信息 -->
    <van-cell-group>
      <van-cell title="患者信息" :value="`${patient?.name} | ${patient?.genderValue} | ${patient?.age}岁`"></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 支付按钮  :price 是分 需要计算*100 -->
    <van-submit-bar button-type="primary" :price="payInfo.actualPayment * 100" :loading="loading" button-text="立即支付"
      text-align="left" @click="openSheet" />



    <!-- 支付方式 抽屉  close-on-popstate="false"  是否在页面回退时自动关闭，防止一闪过-->
    <van-action-sheet v-model:show="show" title="选择支付方式" :closeable="false" :before-close="onClose"
      :close-on-popstate="false">
      <div class="pay-type">
        <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay">立即支付</van-button>
        </div>
      </div>
    </van-action-sheet>
  </div>
  <div class="consult-pay-page" v-else>
    <van-skeleton title :row="3" />
    <van-skeleton title :row="4" />
    <van-skeleton title :row="3" />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}

.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;

  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }

  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }

  .desc {
    flex: 1;

    >span {
      display: block;
      color: var(--cp-tag);

      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}

.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }

    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}

.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}

.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;

  .text {
    color: var(--cp-primary);
  }
}

::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}

.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }

  .btn {
    padding: 15px;
  }

  .van-cell {
    align-items: center;

    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }

    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
